/**
 *  返回图片动态地址
 *
 * @param  imagename 文件名
 **/
export function autoimg(imagename) {
    let re = new URL(`../static/cake/${imagename}`, import.meta.url).href
    return re 
}

/**
 *  返回背景图动态地址
 *
 * @param  imagename 文件名
 **/
export function backgroundImg(imagename, position = '50% 50%', backgroundsize = 'cover') {
    let re = `background: url('${autoimg(imagename)}') no-repeat ${position};background-size: ${backgroundsize};`
    return re
}


// 日期格式化
export function parseTime(time, pattern) {
	if (arguments.length === 0 || !time) {
		return null;
	}
	let format = pattern || "{y}-{m}-{d} {h}:{i}:{s}";
	let date;
	// console.log(time)   //2023-02-18T00:00:00.000+08:00
	if (typeof time === "object") {
		date = time;
	} else {
		if (typeof time === "string" && /^[0-9]+$/.test(time)) {
			time = parseInt(time);
		} else if (typeof time === "string" && time.indexOf("T") > 0) {
			date = new Date(time);
		} else {
			if (typeof time === "string") {
				time = time
					.replace(new RegExp(/-/gm), "/")
					.replace("T", " ")
					.replace(new RegExp(/\.[\d]{3}/gm), "");
			}
			if (typeof time === "number" && time.toString().length === 10) {
				time = time * 1000;
			}
			date = new Date(time); //火狐浏览器new Date有问题,只支持 01/23/2023 18:09:12
		}
	}
	let formatObj = {
		y: date.getFullYear(),
		m: date.getMonth() + 1,
		d: date.getDate(),
		h: date.getHours(),
		i: date.getMinutes(),
		s: date.getSeconds(),
		a: date.getDay(),
	};
	let time_str = format.replace(/{(y|m|d|h|i|s|a)+}/g, (result, key) => {
		let value = formatObj[key];
		// Note: getDay() returns 0 on Sunday
		if (key === "a") {
			return ["日", "一", "二", "三", "四", "五", "六"][value];
		}
		if (result.length > 0 && value < 10) {
			value = "0" + value;
		}
		return value || 0;
	});
	return time_str;
}


/**
 * @description 检测用户授权信息
 * @param name 传入【scope.address、scope.invoice、scope.invoiceTitle、scope.userInfo、scope.userLocation】可检测具体授权项，返回布尔类型; 不传则返回全部授权项，返回对象类型
 * @returns {Promise<unknown>}
 */
export function checkSetting(name) {
  // name可选【scope.address、scope.invoice、scope.invoiceTitle、scope.userInfo、scope.userLocation】
  return new Promise((resolve) => {
    uni.getSetting({
      success: (res) => {
        if (name) {
          resolve(res.authSetting[name] || false)
        } else {
          resolve(res.authSetting || {})
        }
      },
      fail: (err) => {
        if (err && err.errMsg && /connect fail/i.test(err.errMsg)) { // ios频繁调用后，会触发微信限制，就默认true  eg:getSetting:fail connect fail
          resolve(true)
          return
        }
        if (name) {
          resolve(false)
        } else {
          resolve({})
        }
      }
    })
  })
}
